﻿Imports System.Windows.Threading

Public Class DispatcherHelper

    Private Shared exitFrameCallback As New DispatcherOperationCallback(AddressOf ExitFrame)

    ''' <summary>現在メッセージ待ち行列の中にある全てのUIメッセージを処理します</summary>
    Public Shared Sub DoEvents()

        Dim nestedFrame As New DispatcherFrame
        Dim exitOperation As DispatcherOperation = Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, exitFrameCallback, nestedFrame)
        Dispatcher.PushFrame(nestedFrame)

        If exitOperation.Status <> DispatcherOperationStatus.Completed Then exitOperation.Abort()

    End Sub

    ''' <summary>ネスト化されたメッセージループを抜けます</summary>
    Private Shared Function ExitFrame(ByVal state As Object) As Object
        Dim frame = TryCast(state, DispatcherFrame)
        If frame Is Nothing Then Return Nothing
        frame.Continue = False
        Return Nothing
    End Function

End Class
